/*
 * *******************************************************************
 *   @项目名称: BHex Android
 *   @文件名称: MarginAdjustDialog.java
 *   @Date: 19-7-29 下午7:33
 *   @Author: ppzhao
 *   @Description:
 *   @Copyright（C）: 2019 BlueHelix Inc.   All rights reserved.
 *   注意：本内容仅限于内部传阅，禁止外泄以及用于其他的商业目的.
 *  *******************************************************************
 */

package io.bhex.app.trade.ui;

import android.app.Dialog;
import android.content.Context;
import android.content.DialogInterface;
import android.text.Editable;
import android.text.InputFilter;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.EditText;
import android.widget.TextView;

import com.flyco.tablayout.SegmentTabLayout;
import com.flyco.tablayout.listener.OnTabSelectListener;

import java.util.List;

import io.bhex.app.R;
import io.bhex.app.utils.FuturesCalculationFormula;
import io.bhex.app.utils.KlineUtils;
import io.bhex.app.utils.SkinColorUtil;
import io.bhex.app.view.PointLengthFilter;
import io.bhex.app.view.ShadowDrawable;
import io.bhex.baselib.network.Utils.CodeUtils;
import io.bhex.baselib.network.listener.SimpleResponseListener;
import io.bhex.baselib.network.response.ResultResponse;
import io.bhex.baselib.utils.NumberUtils;
import io.bhex.baselib.utils.PixelUtils;
import io.bhex.baselib.utils.ToastUtils;
import io.bhex.sdk.data_manager.SymbolDataManager;
import io.bhex.sdk.quote.bean.CoinPairBean;
import io.bhex.sdk.quote.bean.FuturensBaseToken;
import io.bhex.sdk.quote.bean.RiskLimitBean;
import io.bhex.sdk.trade.AssetApi;
import io.bhex.sdk.trade.bean.FuturesAssetListResponse;
import io.bhex.sdk.trade.bean.FuturesCreateOrderConfig;
import io.bhex.sdk.trade.bean.FuturesCreateOrderConfigResponse;
import io.bhex.sdk.trade.futures.FuturesApi;
import io.bhex.sdk.trade.futures.bean.FuturesPositionOrder;

public class MarginAdjustDialog {
    private final OnDialogObserver mDialogObserver;
    private Context mContext;
    private View mContentView;
    private Dialog bottomDialog;
    private CoinPairBean coinPairBean;

    private int digitBase;
    private int digitAmount;
    private int digitMargin;
    private FuturesPositionOrder mHoldOrderBean;
    private OnLoadingObserver mObserver;
    private SegmentTabLayout marginTab;
    private boolean isIncreaseMargin = true;
    private EditText inputView;
    private TextView forceClosePriceTv;
    private TextView inputMarginUnitTv;
    private TextView maxIncreseMarginTitle;
    private TextView increseMarginTitle;
    private String maxIncreaseAsset = "";
    private TextView marginLimitTv;
    private String maxReduceMargin = "";
    private RiskLimitBean currentRiskLimitBean;

    public interface OnLoadingObserver {
        void showLoading();

        void hideLoading();
    }

    public interface OnDialogObserver {

        void onShow(DialogInterface dialog);

        void onDismiss(DialogInterface dialog);

        void onReqHttpSuccess();

        void onReqHttpFaile();
    }

    public MarginAdjustDialog(Context context, FuturesPositionOrder itemModel, OnLoadingObserver observer, OnDialogObserver dialogObserver) {
        mContext = context;
        mHoldOrderBean = itemModel;
        mObserver = observer;
        mDialogObserver = dialogObserver;
    }

    public void ShowDialog() {
        bottomDialog = new Dialog(mContext, R.style.BottomDialog);
        mContentView = LayoutInflater.from(mContext).inflate(R.layout.margin_adjust_content_circle, null);
        bottomDialog.setContentView(mContentView);
        ViewGroup.MarginLayoutParams params = (ViewGroup.MarginLayoutParams) mContentView.getLayoutParams();
        params.width = mContext.getResources().getDisplayMetrics().widthPixels;
        mContentView.setLayoutParams(params);
        initView();
        bottomDialog.setCanceledOnTouchOutside(true);
        bottomDialog.getWindow().setGravity(Gravity.BOTTOM);
        bottomDialog.getWindow().setWindowAnimations(R.style.BottomDialog_Animation);
        bottomDialog.show();
    }

    private void initView() {
        try {
            marginTab = mContentView.findViewById(R.id.segmentTab);
            marginTab.setTabData(new String[]{mContext.getString(R.string.string_increase_margin), mContext.getString(R.string.string_recrease_margin)});
//            marginTab.setTabData(new String[]{mContext.getString(R.string.string_increase_margin)});
            marginTab.setOnTabSelectListener(new OnTabSelectListener() {
                @Override
                public void onTabSelect(int position) {
                    isIncreaseMargin = position == 0;
                    updateMarginStatus();
                    updateForceClosePrice();
                }

                @Override
                public void onTabReselect(int position) {

                }
            });
            marginTab.setCurrentTab(0);//默认是增加保证金

            if (mHoldOrderBean != null && mContentView != null) {
                coinPairBean = SymbolDataManager.GetInstance().getSymbolInfoById(mHoldOrderBean.getSymbolId());
                if (coinPairBean == null) {
                    ToastUtils.showShort(mContext.getResources().getString(R.string.string_data_exception));
                    if (bottomDialog.isShowing()) {
                        bottomDialog.dismiss();
                    }
                    return;
                }
                digitBase = NumberUtils.calNumerCount(mContext, coinPairBean.getBasePrecision());
                digitAmount = NumberUtils.calNumerCount(mContext, coinPairBean.getQuotePrecision());
                FuturensBaseToken baseTokenFutures = coinPairBean.baseTokenFutures;
                if (baseTokenFutures != null) {
                    digitMargin = NumberUtils.calNumerCount(mContext, baseTokenFutures.getMarginPrecision());
                }

                maxReduceMargin = mHoldOrderBean.getMinMargin();
                //isLong 仓位方向: 1=多仓，0=空仓
                String positionSide = KlineUtils.getFuturesOrderPositionTxtByIsLong(mContext, mHoldOrderBean.getIsLong());
                int color = KlineUtils.getFuturesOrderSideColorByIsLong(mContext, mHoldOrderBean.getIsLong());
                maxIncreseMarginTitle = mContentView.findViewById(R.id.title_max_increase_margin);
                increseMarginTitle = mContentView.findViewById(R.id.title_increase_margin);
                ((TextView) mContentView.findViewById(R.id.value_contract_type)).setText(positionSide);
                ((TextView) mContentView.findViewById(R.id.value_contract_type)).setTextColor(color);
                ((TextView) mContentView.findViewById(R.id.value_contract_name)).setText(mHoldOrderBean.getSymbolName());
                ((TextView) mContentView.findViewById(R.id.value_contract_hold)).setText(mHoldOrderBean.getTotal());
                ((TextView) mContentView.findViewById(R.id.value_hold_margin)).setText(mHoldOrderBean.getMargin()+mHoldOrderBean.getUnit());
                marginLimitTv = mContentView.findViewById(R.id.value_max_increase_margin);
                inputMarginUnitTv = mContentView.findViewById(R.id.inputMarginUnit);
                forceClosePriceTv = mContentView.findViewById(R.id.value_force_close_price);
                inputView = mContentView.findViewById(R.id.input_increase_margin);
                inputView.setHint(mContext.getString(R.string.string_input_margin_please));
                inputView.addTextChangedListener(new TextWatcher() {
                    @Override
                    public void beforeTextChanged(CharSequence s, int start, int count, int after) {

                    }

                    @Override
                    public void onTextChanged(CharSequence s, int start, int before, int count) {
                        boolean isOk = checkInputMarginRange(s.toString().trim());
                        if (isOk) {
                            calForceClosePrice(s.toString().trim());
                        }
                    }

                    @Override
                    public void afterTextChanged(Editable s) {

                    }
                });

                mContentView.findViewById(R.id.btnSure).setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {


                        String amount = inputView.getText().toString().trim();
                        if (TextUtils.isEmpty(amount)) {
                            if (isIncreaseMargin) {
                                ToastUtils.showShort(mContext, mContext.getString(R.string.string_input_please) + mContext.getString(R.string.string_increase_margin));
                            } else {
                                ToastUtils.showShort(mContext, mContext.getString(R.string.string_input_please) + mContext.getString(R.string.string_recrease_margin));
                            }
                            return;
                        }

                        adjustMargin(mHoldOrderBean.getSymbolId(), isIncreaseMargin, amount, mHoldOrderBean.getIsLong());
                    }
                });

                mContentView.findViewById(R.id.close).setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        bottomDialog.dismiss();
                    }
                });

//                PointLengthFilter pricePointFilter = new PointLengthFilter();
                PointLengthFilter amountPointFilter = new PointLengthFilter();
//
//                pricePointFilter.setDecimalLength(digitAmount);
                amountPointFilter.setDecimalLength(digitMargin);
                inputView.setFilters(new InputFilter[]{amountPointFilter});
                inputMarginUnitTv.setText(mHoldOrderBean.getUnit());

                marginLimitTv.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        inputView.setText(isIncreaseMargin ? maxIncreaseAsset : maxReduceMargin);

                    }
                });

            }

            getAseet(mHoldOrderBean.getUnit());
            getMarginRate(mHoldOrderBean);

        } catch (Exception e) {
        }


    }

    /**
     * 校验输入保证金是否超出最大可增加或要减少的保证金限额
     * @param inputMargin
     * @return
     */
    private boolean checkInputMarginRange(String inputMargin) {
        if (isIncreaseMargin) {
            if (NumberUtils.sub(inputMargin,maxIncreaseAsset)>0) {
                inputView.setText(maxIncreaseAsset);
                return false;
            }else{
                return true;
            }
        }else{
            if (NumberUtils.sub(inputMargin,maxReduceMargin)>0) {
                inputView.setText(maxReduceMargin);
                return false;
            }else{
                return true;
            }
        }

    }

    private void updateForceClosePrice() {
        String inputMargin = inputView.getText().toString().trim();
        calForceClosePrice(inputMargin);
    }

    /**
     * 获取保证金率
     * @param mHoldOrderBean
     */
    private void getMarginRate(final FuturesPositionOrder mHoldOrderBean) {
        if (mHoldOrderBean != null) {
            FuturesApi.getFuturesCreateOrderConfig(mHoldOrderBean.getExchangeId(),mHoldOrderBean.getSymbolId(),new SimpleResponseListener<FuturesCreateOrderConfigResponse>(){
                @Override
                public void onSuccess(FuturesCreateOrderConfigResponse response) {
                    super.onSuccess(response);
                    if (CodeUtils.isSuccess(response,true)) {
                        List<FuturesCreateOrderConfig> dataConfigs = response.getArray();
                        if (dataConfigs != null && dataConfigs.size() > 0) {
                            FuturesCreateOrderConfig futuresCreateOrderConfig = dataConfigs.get(0);
                            List<RiskLimitBean> riskLimit = futuresCreateOrderConfig.getRiskLimit();
                            for (RiskLimitBean riskLimitBean : riskLimit) {
                                if (riskLimitBean.getSide().equals(KlineUtils.getFuturesOpenSideByIsLong(mContext,mHoldOrderBean.getIsLong()))) {
                                    currentRiskLimitBean = riskLimitBean;
                                }
                            }

                        }
                    }
                }
            });

        }
    }

    /**
     * 获取资产
     *
     * @param tokenId
     */
    private void getAseet(String tokenId) {
        AssetApi.RequestFuturesTokenIdAsset(tokenId, new SimpleResponseListener<FuturesAssetListResponse>() {
            @Override
            public void onFinish() {
                super.onFinish();
            }

            @Override
            public void onSuccess(FuturesAssetListResponse response) {
                super.onSuccess(response);
                if (CodeUtils.isSuccess(response, true)) {
                    List<FuturesAssetListResponse.FuturesAssetBean> data = response.array;
                    if (data != null) {
                        if (data.size() > 0) {
                            FuturesAssetListResponse.FuturesAssetBean assetBean = data.get(0);
                            if (assetBean != null) {
                                maxIncreaseAsset = assetBean.availableMargin;
                                maxIncreaseAsset = NumberUtils.roundFormatDown(maxIncreaseAsset,digitMargin);
                                updateMarginAssetLimit();
                            }
                        }
                    }
                }
            }

            @Override
            public void onError(Throwable error) {
                super.onError(error);
            }
        });
    }

    /**
     * 更新调整保证金的限额
     */
    private void updateMarginAssetLimit() {
        if (mHoldOrderBean != null) {
            if (isIncreaseMargin) {
                marginLimitTv.setText(TextUtils.isEmpty(maxIncreaseAsset) ? "0" : maxIncreaseAsset + " " + mHoldOrderBean.getUnit());
            } else {
                marginLimitTv.setText(TextUtils.isEmpty(maxReduceMargin) ? "0" : maxReduceMargin + " " + mHoldOrderBean.getUnit());
            }
        }
    }

    /**
     * 调整保证金
     *
     * @param symbolId
     * @param isIncreaseMargin
     * @param amount
     * @param isLong
     */
    private void adjustMargin(String symbolId, boolean isIncreaseMargin, String amount, String isLong) {
        FuturesApi.adjustMargin(symbolId, isIncreaseMargin ? "INC" : "DEC", amount, isLong, new SimpleResponseListener<ResultResponse>() {
            @Override
            public void onBefore() {
                super.onBefore();
                if (mObserver != null)
                    mObserver.showLoading();
            }

            @Override
            public void onFinish() {
                super.onFinish();
                if (mObserver != null)
                    mObserver.hideLoading();
            }

            @Override
            public void onSuccess(ResultResponse response) {
                super.onSuccess(response);
                if (CodeUtils.isSuccess(response, true)) {
                    if (response.isSuccess()) {
                        ToastUtils.showShort(mContext.getString(R.string.string_submit_success));
                        if (bottomDialog != null && bottomDialog.isShowing()) {
                            bottomDialog.dismiss();
                        }
                        if (mDialogObserver != null) {
                            mDialogObserver.onReqHttpSuccess();
                        }
                    } else {
                        ToastUtils.showShort(mContext.getString(R.string.string_submit_failed));
                    }
                }
            }

            @Override
            public void onError(Throwable error) {
                super.onError(error);
                ToastUtils.showShort(mContext.getString(R.string.string_submit_failed));
            }
        });
    }

    private void updateMarginStatus() {
        if (isIncreaseMargin) {
            maxIncreseMarginTitle.setText(mContext.getString(R.string.string_max_increase_margin_point));
            increseMarginTitle.setText(mContext.getString(R.string.string_increase_margin_point));
        } else {
            maxIncreseMarginTitle.setText(mContext.getString(R.string.string_max_reduce_margin_point));
            increseMarginTitle.setText(mContext.getString(R.string.string_reduce_margin_point));
        }
        updateMarginAssetLimit();
    }

    /**
     * 计算强制平仓价
     *
     * @param inputMargin
     */
    private void calForceClosePrice(String inputMargin) {
        if (!TextUtils.isEmpty(inputMargin) && mHoldOrderBean!=null && currentRiskLimitBean!=null) {
            String forceClosePrice = FuturesCalculationFormula.calForceClosePrice(isIncreaseMargin ? inputMargin : "-"+inputMargin, mHoldOrderBean,currentRiskLimitBean);

            forceClosePriceTv.setText(forceClosePrice);
        } else {
            forceClosePriceTv.setText("");
        }

    }

    private void setShadow(View view) {
        ShadowDrawable.setShadowDrawable(view,
//                getResources().getColor(R.color.white),
                PixelUtils.dp2px(2),
                SkinColorUtil.getDark10(mContext),
                PixelUtils.dp2px(2),
                0,
                PixelUtils.dp2px(1));
    }
}
